import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_shop/cons/global_cons.dart';
import 'package:flutter_shop/eventbus/event_bus.dart';
import 'package:flutter_shop/pages/base/base_presenter.dart';
import 'package:flutter_shop/pages/base/base_state.dart';
import 'package:flutter_shop/pages/category/category_tab_page/category_tab_model.dart';
import 'package:flutter_shop/pages/category/category_tab_page/entity/category_goods_data.dart';
import 'package:flutter_shop/pages/category/category_tab_page/provider/sub_category_goods_page_provider.dart';
import 'package:flutter_shop/pages/home/home_router.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:flutter_shop/res/dimens.dart';
import 'package:flutter_shop/res/styles.dart';
import 'package:flutter_shop/routers/navigator_utils.dart';
import 'package:flutter_shop/utils/utils.dart';
import 'package:flutter_shop/widget/load_image.dart';
import 'package:flutter_shop/widget/page_state_widget.dart';
import 'package:provider/provider.dart';

///子分类商品
class SubCategoryGoods extends StatefulWidget {
  ///event刷新的tag
  static const REFRESH = "SubCategoryGoodsRefresh";

  @override
  _SubCategoryGoodsState createState() => _SubCategoryGoodsState();
}

class _SubCategoryGoodsState extends BaseState<SubCategoryGoods, BasePresenter> {
  List<CategoryGoodsData> mDatas = [];
  int currentIndex = 1;

  ScrollController scrollController = ScrollController();
  EasyRefreshController refreshController;

  @override
  bool get useEventBus => true;

  @override
  void onEventBus(EventMessage event) {
    switch (event.tag) {
      case SubCategoryGoods.REFRESH:
        //刷新数据
        setState(() {
          currentIndex = 1;
        });
        pageStateController.showLoading();
        _requestGetCategoryGoods(event.str1, event.str2);
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<SubCategoryGoodsPageProvider>(
      builder: (_, provider, child) {
        refreshController = provider.refreshController;

        return PageStateWidget(
            controller: pageStateController,
            retryClick: () {
              setState(() {
                currentIndex = 1;
              });
              pageStateController.showLoading();
              _requestGetCategoryGoods(provider.categoryId, provider.categorySubId);
            },
            child: EasyRefresh(
              controller: provider.refreshController,
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              onRefresh: () async {
                setState(() {
                  currentIndex = 1;
                });
                _requestGetCategoryGoods(provider.categoryId, provider.categorySubId);
              },
              onLoad: () async {
                _requestGetCategoryGoods(provider.categoryId, provider.categorySubId);
              },
              child: ListView.builder(
                controller: scrollController,
                itemCount: mDatas.length,
                itemBuilder: _buildItem,
              ),
            ));
      },
    );
  }

  Widget _buildItem(context, index) {
    CategoryGoodsData item = mDatas[index];

    return RawMaterialButton(
      fillColor: Colors.white,
      onPressed: () {
        NavigatorUtils.push(context, HomeRouter.goodDetail, params: {GlobalCons.KEY_ID: item.goodsId});
      },
      child: Container(
        padding: Paddings.common,
        decoration: BoxDecoration(border: Borders.bottom),
        child: Row(
          children: <Widget>[
            LoadImage(
              item.image,
              width: ScreenUtil().setWidth(150),
            ),
            Expanded(
                child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text(
                  item.goodsName,
                  style: TextStyles.common_text,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                Gaps.v_gap_15,
                Row(
                  children: <Widget>[
                    Text(
                      "¥${item.presentPrice}",
                      style: TextStyles.primary_text,
                    ),
                    Text(
                      "¥${item.oriPrice}",
                      style: TextStyle(
                        fontSize: CommonDimens.font_size_small,
                        color: CommonColors.gray,
                        decoration: TextDecoration.lineThrough,
                      ),
                    ),
                  ],
                )
              ],
            )),
          ],
        ),
      ),
    );
  }

  ///请求获取分类下的商品
  void _requestGetCategoryGoods(String categoryId, String categorySubId) {
    CategoryTabModel().getCategoryGoodsData(categoryId, categorySubId, currentIndex).then((val) {
      pageStateController.showSuccess();
      if (val == null) {
        val = List<CategoryGoodsData>();
      }
      if (currentIndex == 1 && val.isEmpty) {
        pageStateController.showEmpty();
      }

      setState(() {
        if (currentIndex == 1) {
          refreshController?.resetLoadState();
          mDatas.clear();
        }
        mDatas.addAll(val);
        currentIndex++;
      });
      refreshController?.finishRefresh(success: true);
      refreshController?.finishLoad(success: true, noMore: val.isEmpty);
    }).catchError((error) {
      pageStateController.showError(error.message);
      refreshController?.finishLoad(success: false);
      Utils.showToast(error.message);
    });
  }
}
